import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/home/home_logic.dart';

import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/app_user_info_model.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';

import 'package:flutter_09_game/utils/shared/shared_key.dart';
import 'package:flutter_09_game/utils/shared/shared_storage.dart';
import 'package:get/get.dart';

class LoginLogic extends BaseController {
  TextEditingController loginAccountC = TextEditingController();
  TextEditingController loginPwdC = TextEditingController();

  TextEditingController registerAccountC = TextEditingController();
  TextEditingController registerPwdC = TextEditingController();
  TextEditingController registerPwdAgainC = TextEditingController();
  TextEditingController registerCodeC = TextEditingController();

  bool isRegisterTypeRx = Get.arguments?['isRegisterType'] ?? false;

  // 登录按钮启用状态
  RxBool isLoginEnabled = false.obs;

  // 注册按钮启用状态
  RxBool isRegisterEnabled = false.obs;

  // 记住密码状态
  RxBool rememberPassword = false.obs;

  @override
  void onInit() {
    super.onInit();

    // 添加输入监听器
    loginAccountC.addListener(_validateInput);
    loginPwdC.addListener(_validateInput);
    registerAccountC.addListener(_validateInput);
    registerPwdC.addListener(_validateInput);
    registerPwdAgainC.addListener(_validateInput);
    registerCodeC.addListener(_validateInput);

    // 加载保存的登录信息
    _loadSavedLoginInfo();

    if (kDebugMode) {
      // loginAccountC.text = 'level1';
      loginAccountC.text = 'junmx6_363';
      loginAccountC.text = 'junmx2';
      loginAccountC.text = 'dataosha_A';


      //
      loginPwdC.text = '123456';

    }
  }

  @override
  void onClose() {
    loginAccountC.removeListener(_validateInput);
    loginPwdC.removeListener(_validateInput);

    registerAccountC.removeListener(_validateInput);
    registerPwdC.removeListener(_validateInput);
    registerPwdAgainC.removeListener(_validateInput);
    registerCodeC.removeListener(_validateInput);

    loginAccountC.dispose();
    loginPwdC.dispose();
    registerAccountC.dispose();
    registerPwdC.dispose();
    registerPwdAgainC.dispose();
    registerCodeC.dispose();
    super.onClose();
  }

  /// 验证账户输入
  /// 规则：长度 >= 3位，只能是数字或字母
  bool _validateAccount(String account) {
    if (account.length < 3) return false;
    // 检查是否只包含数字和字母
    return RegExp(r'^[a-zA-Z0-9_]+$').hasMatch(account);
  }

  /// 验证密码输入
  /// 规则：长度在6-10位之间
  bool _validatePassword(String password) {
    return password.length >= 6 && password.length <= 16;
  }

  /// 验证密码匹配
  /// 规则：两次输入的密码必须一致
  bool _validatePasswordMatch() {
    return registerPwdC.text.isNotEmpty &&
        registerPwdAgainC.text.isNotEmpty &&
        registerPwdC.text == registerPwdAgainC.text;
  }

  /// 验证注册输入
  /// 规则：账户、密码、确认密码、邀请码都必须有效
  bool _validateRegisterInput() {
    final accountValid = _validateAccount(registerAccountC.text);
    final passwordValid = _validatePassword(registerPwdC.text);
    final passwordMatchValid = registerPwdAgainC.text.length >= 6;
    // 邀请码可以为空，如果不为空则需要至少3位
    final inviteCodeValid =
        registerCodeC.text.isEmpty || registerCodeC.text.length >= 3;

    return accountValid &&
        passwordValid &&
        passwordMatchValid &&
        inviteCodeValid;
  }

  /// 综合验证输入并更新按钮状态
  void _validateInput() {
    if (isRegisterTypeRx) {
      // 注册模式验证
      isRegisterEnabled.value = _validateRegisterInput();
      isLoginEnabled.value = false; // 注册模式下禁用登录按钮
    } else {
      // 登录模式验证
      final accountValid = _validateAccount(loginAccountC.text);
      final passwordValid = _validatePassword(loginPwdC.text);
      isLoginEnabled.value = accountValid && passwordValid;
      isRegisterEnabled.value = false; // 登录模式下禁用注册按钮
    }
  }

  /// 手动触发验证（供外部调用）
  void validateInput() {
    _validateInput();
  }

  /// 加载保存的登录信息
  void _loadSavedLoginInfo() {
    String? savedAccount =
        SharedStorage().prefs.getString(SharedKey.savedAccount);
    String? savedPassword =
        SharedStorage().prefs.getString(SharedKey.savedPassword);
    bool? savedRememberPassword =
        SharedStorage().prefs.getBool(SharedKey.rememberPassword);

    if (savedAccount != null) {
      loginAccountC.text = savedAccount;
    }

    if (savedRememberPassword == true && savedPassword != null) {
      loginPwdC.text = savedPassword;
      rememberPassword.value = true;
    }

    // 触发验证
    _validateInput();
  }

  /// 保存登录信息
  void _saveLoginInfo() {
    SharedStorage().prefs.setString(SharedKey.savedAccount, loginAccountC.text);
    SharedStorage()
        .prefs
        .setBool(SharedKey.rememberPassword, rememberPassword.value);
    if (rememberPassword.value) {
      if (rememberPassword.value) {
        SharedStorage()
            .prefs
            .setString(SharedKey.savedPassword, loginPwdC.text);
      } else {
        SharedStorage().prefs.remove(SharedKey.savedPassword);
      }
    }
  }

  /// 切换记住密码状态
  void toggleRememberPassword(bool value) {
    rememberPassword.value = value;
    if (!value) {
      // 如果取消记住密码，清除保存的密码
      SharedStorage().prefs.remove(SharedKey.savedPassword);
    }
  }

  /// 执行登录
  Future<void> login() async {
    if (!isLoginEnabled.value) {
      return;
    }

    try {
      // 获取IP地址
      String ipAddress ='';
      // SharedStorage().prefs.getString(
      //           SharedKey.lastLoginIp,
      //         ) ??
      //     "";


      // 发起登录请求
      HttpResponse response = await HttpManager().post(
        API.postUserLogin,
        params: {
          'password': loginPwdC.text.trim(),
          'username': loginAccountC.text.trim(),
          'last_login_ip': ipAddress,
        },
        fromJson: AppUserInfoModel.fromJson,
        uiType: HttpUIType.loadingAndToast,
      );

      if (response.isSuccess) {
        AppUserInfoModel infoModel = response.data;
        _saveLoginInfo();

        if (infoModel.token != null) {
          await AppUserManager().updateToken(infoModel.token);
          await AppUserManager().updateUserInfo(infoModel.user!);
          await AppUserManager().loadWalletData();

          SharedStorage().prefs.setString(
              SharedKey.lastLoginIp, infoModel.user?.lastLoginIp ?? '');
          // Get.until((route) => Get.currentRoute == AppRoutes.main);
          LoadingUtils.showToast(LocaleKeys.loginSuccess.tr);
          Get.back();
          if (Get.isRegistered<HomeLogic>()) {
            Get.find<HomeLogic>().refreshList();
          }
        }
      }
    } catch (e) {
      // 网络请求异常已由HttpManager处理，这里不需要额外处理
      print('登录异常: $e');
    }
  }

  /// 执行注册
  Future<void> register() async {
    if (!_validatePasswordMatch()) {
      LoadingUtils.showToast(LocaleKeys.passwordMismatch.tr);
      return;
    }
    // 获取IP地址
    String ipAddress = SharedStorage().prefs.getString(
              SharedKey.lastLoginIp,
            ) ??
        "";

    // 发起注册请求
    HttpResponse response = await HttpManager().post(
      API.postUserRegister,
      params: {
        'username': registerAccountC.text.trim(),
        'password': registerPwdC.text.trim(),
        'password_confirm': registerPwdAgainC.text.trim(),
        'invite_code': registerCodeC.text.trim().isEmpty
            ? null
            : registerCodeC.text.trim(),
        'register_ip': ipAddress,
      },
      fromJson: AppUserInfoModel.fromJson,
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      AppUserInfoModel infoModel = response.data;
      _saveLoginInfo();

      if (infoModel.token != null) {
        await AppUserManager().updateToken(infoModel.token);
        await AppUserManager().updateUserInfo(infoModel.user!);
        await AppUserManager().loadWalletData();

        SharedStorage().prefs.setString(
            SharedKey.lastLoginIp, infoModel.user?.lastLoginIp ?? '');
        LoadingUtils.showToast(LocaleKeys.registerSuccess.tr);
        Get.back();
        if (Get.isRegistered<HomeLogic>()) {
          Get.find<HomeLogic>().refreshList();
        }
      }
    } else if (response.msg?.contains('Invalid invite code') == true) {
      LoadingUtils.showToast(LocaleKeys.inviteCodeInvalid.tr);
    }
  }

  /// 忘记密码
  void forgotPassword() {
    AppUserManager().showServiceSheet();
    // TODO: 实现忘记密码功能
    // LoadingUtils.showToast('忘记密码功能待实现');
  }

  /// 注册账户
  void registerAccount(bool isRegister) {
    isRegisterTypeRx = isRegister;
    // 切换模式后重新验证输入
    _validateInput();
    update();
  }
}
